<template>
  <div class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
    <div class="rounded-lg shadow-xl max-w-lg w-full mx-4 max-h-[85vh] overflow-y-auto transition-colors duration-300"
         :class="themeStore.theme.bg.modal">
      <!-- 模态框头部 -->
      <div class="flex items-center justify-between p-4 border-b transition-colors duration-300"
           :class="themeStore.theme.border.primary">
        <h2 class="text-lg font-semibold" :class="themeStore.theme.text.primary">设置</h2>
        <button
          @click="$emit('close')"
          class="p-2 rounded-md transition-colors duration-200"
          :class="[
            themeStore.theme.text.tertiary,
            themeStore.theme.hover,
            'hover:' + themeStore.theme.text.primary
          ]"
        >
          <font-awesome-icon :icon="['fas', 'times']" class="h-5 w-5" />
        </button>
      </div>

      <!-- 设置内容 -->
      <div class="p-4 space-y-4">
        <!-- 账户设置 -->
        <div class="space-y-3">
          <h3 class="text-base font-medium text-white border-b border-gray-800/30 pb-2">
            <font-awesome-icon :icon="['fas', 'user-cog']" class="mr-2" />
            账户设置
          </h3>

          <!-- 修改密码 -->
          <div class="bg-gray-700 rounded-lg p-3">
            <h4 class="text-sm text-white font-medium mb-3">修改密码</h4>
            <div class="space-y-2.5">
              <div>
                <label class="block text-xs text-gray-300 mb-1">当前密码</label>
                <div class="relative">
                  <input
                    v-model="passwordForm.currentPassword"
                    :type="showCurrentPassword ? 'text' : 'password'"
                    class="w-full px-3 py-2 text-sm bg-gray-600 border border-gray-500 rounded-md text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                    placeholder="请输入当前密码"
                  />
                  <button
                    type="button"
                    @click="showCurrentPassword = !showCurrentPassword"
                    class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-white"
                  >
                    <font-awesome-icon :icon="['fas', showCurrentPassword ? 'eye-slash' : 'eye']" />
                  </button>
                </div>
              </div>
              
              <div>
                <label class="block text-xs text-gray-300 mb-1">新密码</label>
                <div class="relative">
                  <input
                    v-model="passwordForm.newPassword"
                    :type="showNewPassword ? 'text' : 'password'"
                    class="w-full px-3 py-2 text-sm bg-gray-600 border border-gray-500 rounded-md text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                    :class="{ 'border-red-500': passwordValidation.newPasswordTooShort || passwordValidation.sameAsCurrentPassword }"
                    placeholder="请输入新密码（至少6位）"
                  />
                  <button
                    type="button"
                    @click="showNewPassword = !showNewPassword"
                    class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-white"
                  >
                    <font-awesome-icon :icon="['fas', showNewPassword ? 'eye-slash' : 'eye']" />
                  </button>
                </div>
                <!-- 新密码验证提示 -->
                <div v-if="passwordForm.newPassword" class="mt-1 text-xs">
                  <div v-if="passwordValidation.newPasswordTooShort" class="text-red-400">
                    ❌ 密码长度至少6位
                  </div>
                  <div v-else-if="passwordValidation.sameAsCurrentPassword" class="text-red-400">
                    ❌ 新密码不能与当前密码相同
                  </div>
                  <div v-else class="text-green-400">
                    ✅ 密码长度符合要求
                  </div>
                </div>
              </div>
              
              <div>
                <label class="block text-xs text-gray-300 mb-1">确认新密码</label>
                <div class="relative">
                  <input
                    v-model="passwordForm.confirmPassword"
                    :type="showConfirmPassword ? 'text' : 'password'"
                    class="w-full px-3 py-2 text-sm bg-gray-600 border border-gray-500 rounded-md text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
                    :class="{ 'border-red-500': passwordValidation.passwordsNotMatch }"
                    placeholder="请再次输入新密码"
                  />
                  <button
                    type="button"
                    @click="showConfirmPassword = !showConfirmPassword"
                    class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-white"
                  >
                    <font-awesome-icon :icon="['fas', showConfirmPassword ? 'eye-slash' : 'eye']" />
                  </button>
                </div>
                <!-- 确认密码验证提示 -->
                <div v-if="passwordForm.confirmPassword" class="mt-1 text-xs">
                  <div v-if="passwordValidation.passwordsNotMatch" class="text-red-400">
                    ❌ 两次输入的密码不一致
                  </div>
                  <div v-else class="text-green-400">
                    ✅ 密码确认一致
                  </div>
                </div>
              </div>
              
              <button
                @click="changePassword"
                :disabled="!canChangePassword || isChangingPassword"
                class="w-full px-3 py-2 text-sm bg-indigo-600 hover:bg-indigo-700 disabled:bg-gray-600 disabled:cursor-not-allowed text-white rounded-md transition-colors duration-200 flex items-center justify-center"
              >
                <font-awesome-icon
                  v-if="isChangingPassword"
                  :icon="['fas', 'spinner']"
                  class="animate-spin mr-2"
                />
                {{ isChangingPassword ? '修改中...' : '修改密码' }}
              </button>
            </div>
          </div>
        </div>

        <!-- 外观设置 -->
        <div class="space-y-3">
          <h3 class="text-base font-medium text-white border-b border-gray-800/30 pb-2">
            <font-awesome-icon :icon="['fas', 'palette']" class="mr-2" />
            外观设置
          </h3>

          <div class="bg-gray-700 rounded-lg p-3 space-y-3">
            <!-- 主题切换 -->
            <div class="flex items-center justify-between">
              <div>
                <label class="text-sm text-white font-medium">深色模式</label>
                <p class="text-xs text-gray-400">切换应用的外观主题</p>
              </div>
              <button
                @click="themeStore.toggleTheme()"
                :class="[
                  'relative inline-flex h-5 w-9 items-center rounded-full transition-colors duration-200',
                  themeStore.currentTheme === 'dark' ? 'bg-indigo-600' : 'bg-gray-600'
                ]"
              >
                <span
                  :class="[
                    'inline-block h-3 w-3 transform rounded-full bg-white transition-transform duration-200',
                    themeStore.currentTheme === 'dark' ? 'translate-x-5' : 'translate-x-1'
                  ]"
                />
              </button>
            </div>
          </div>
        </div>

        <!-- 数据管理 -->
        <div class="space-y-4">
          <h3 class="text-lg font-medium text-white bg-gradient-to-r from-gray-800/50 to-transparent px-3 py-2 rounded-md mb-2">
            <font-awesome-icon :icon="['fas', 'database']" class="mr-2" />
            数据管理
          </h3>
          
          <div class="bg-gray-700 rounded-lg p-4 space-y-3">
            <button
              @click="exportData"
              class="w-full px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md transition-colors duration-200 flex items-center justify-center"
            >
              <font-awesome-icon :icon="['fas', 'download']" class="mr-2" />
              导出聊天记录
            </button>
            
            <button
              @click="clearAllData"
              class="w-full px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-md transition-colors duration-200 flex items-center justify-center"
            >
              <font-awesome-icon :icon="['fas', 'trash']" class="mr-2" />
              清除所有数据
            </button>
          </div>
        </div>
      </div>


    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useThemeStore } from '../stores/theme'
import api from '../api/index.js'

export default {
  name: 'Settings',
  emits: ['close'],
  setup() {
    // 主题管理
    const themeStore = useThemeStore()

    const passwordForm = ref({
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    const showCurrentPassword = ref(false)
    const showNewPassword = ref(false)
    const showConfirmPassword = ref(false)
    const isChangingPassword = ref(false)
    
    const canChangePassword = computed(() => {
      return passwordForm.value.currentPassword &&
             passwordForm.value.newPassword &&
             passwordForm.value.confirmPassword &&
             passwordForm.value.newPassword === passwordForm.value.confirmPassword &&
             passwordForm.value.newPassword.length >= 6 &&
             passwordForm.value.currentPassword !== passwordForm.value.newPassword  // 新密码不能与当前密码相同
    })

    // 密码验证提示
    const passwordValidation = computed(() => {
      const validation = {
        currentPasswordEmpty: !passwordForm.value.currentPassword,
        newPasswordEmpty: !passwordForm.value.newPassword,
        newPasswordTooShort: passwordForm.value.newPassword && passwordForm.value.newPassword.length < 6,
        passwordsNotMatch: passwordForm.value.newPassword && passwordForm.value.confirmPassword &&
                          passwordForm.value.newPassword !== passwordForm.value.confirmPassword,
        sameAsCurrentPassword: passwordForm.value.currentPassword && passwordForm.value.newPassword &&
                              passwordForm.value.currentPassword === passwordForm.value.newPassword
      }

      return validation
    })
    

    
    const changePassword = async () => {
      if (!canChangePassword.value) return

      // 检查新密码是否与当前密码相同
      if (passwordForm.value.currentPassword === passwordForm.value.newPassword) {
        alert('新密码不能与当前密码相同，请输入不同的密码')
        return
      }

      isChangingPassword.value = true
      try {
        console.log('🔐 [Settings] 开始修改密码...')

        const response = await api.changePassword({
          current_password: passwordForm.value.currentPassword,
          new_password: passwordForm.value.newPassword
        })

        console.log('✅ [Settings] 密码修改成功:', response)

        // 清空表单
        passwordForm.value = {
          currentPassword: '',
          newPassword: '',
          confirmPassword: ''
        }

        alert('密码修改成功！请使用新密码重新登录。')

        // 可选：自动登出用户，让其重新登录
        // window.location.reload()

      } catch (error) {
        console.error('❌ [Settings] 修改密码失败:', error)

        // 提取错误信息
        let errorMessage = '未知错误'

        if (error.response?.data?.message) {
          errorMessage = error.response.data.message
        } else if (error.message) {
          errorMessage = error.message
        } else if (typeof error === 'string') {
          errorMessage = error
        }

        // 翻译常见的英文错误信息
        const errorTranslations = {
          'New password must be different from current password': '新密码必须与当前密码不同',
          'Current password is incorrect': '当前密码不正确',
          'Password must be at least 6 characters': '密码长度至少6位',
          'Invalid password format': '密码格式不正确',
          'User not found': '用户不存在',
          'Authentication failed': '身份验证失败'
        }

        const translatedMessage = errorTranslations[errorMessage] || errorMessage

        alert(`修改密码失败：${translatedMessage}`)
      } finally {
        isChangingPassword.value = false
      }
    }
    

    
    const exportData = async () => {
      try {
        // 这里应该调用API获取用户数据
        const data = {
          conversations: [], // 从API获取
          exportDate: new Date().toISOString()
        }
        
        const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' })
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `chat-data-${new Date().toISOString().split('T')[0]}.json`
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        URL.revokeObjectURL(url)
      } catch (error) {
        console.error('导出数据失败:', error)
        alert('导出数据失败')
      }
    }
    
    const clearAllData = () => {
      if (confirm('确定要清除所有聊天数据吗？此操作不可恢复！')) {
        if (confirm('请再次确认：这将删除所有对话记录和设置！')) {
          // 清除本地存储
          localStorage.clear()
          
          // 这里应该调用API清除服务器数据
          // await api.clearAllUserData()
          
          alert('所有数据已清除')
          location.reload()
        }
      }
    }
    

    
    return {
      themeStore,
      passwordForm,
      showCurrentPassword,
      showNewPassword,
      showConfirmPassword,
      isChangingPassword,
      canChangePassword,
      passwordValidation,
      changePassword,
      exportData,
      clearAllData
    }
  }
}
</script>

